﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Data.Linq;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraPrinting.Native;
using MINERP.ComControls;
using MINERP.FactoryTech.Presenter;
using MINERP.FactoryTech.IView;
using MINERP.MODEL.FactoryTech;
using Leadtools.Codecs;
using Leadtools;
using MINERP.BLL.QC;
using Leadtools.WinForms;
using MINERP.COM;
using MINERP.ComControls.Extension;

namespace MINERP.FactoryTech
{
    public partial class FrmMain : FrmParent, IMainView
    {

        private MainPresenter _presenter;
        Speech _speech;
        List<int> taskTechlist = new List<int>();
        List<TaskInfo> ListTask = new List<TaskInfo>();
        public FrmMain()
        {
            InitializeComponent();
            _presenter = new MainPresenter(this);
            gvTask.ShowRowIndicator(50);
        }

        #region 成员

        /// <summary>
        /// 显示任务
        /// </summary>
        /// <param name="list"></param>
        public void ShowTasks(List<TaskInfo> list)
        {
            ListTask = list;
            gcTask.DataSource = ListTask;
            gcTask.RefreshDataSource();

        }

        public string CurrBarCode { get; set; }
        #endregion

        private void Form1_Load(object sender, EventArgs e)
        {
            _speech = new Speech();
            tssTxtUserName.Text = userName;
            taskTechlist = operates.Select(s => s.Key).ToList();
            RasterCodecs.Startup();
            comboBoxScantype.SelectedIndex = Properties.Settings.Default.Scantype;
            chkPrintBarcode.Checked=Properties.Settings.Default.IsAutoPrintBarcode ;
            //string textName = "";
            //for(var a in base.operates)
            //{

            //}
            //this.Text=
            _presenter.ShowTask(taskTechlist);
            splitContainer1.Panel2Collapsed = true;
            splitContainer1.Panel1Collapsed = false;

            string strTechName = "";
            operates.ForEach(ec =>
            {
                strTechName += ec.Value + ",";
            });
            strTechName = strTechName.Trim(',');
            this.Text = Text + strTechName;
        }

        private void groupControl1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void txtProductBarCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            //Scan(e);
        }

        private void FrmMain_KeyPress(object sender, KeyPressEventArgs e)
        {
            Scan(e);
        }

        private void Scan(KeyPressEventArgs e)
        {
            try  
            {
                if (e.KeyChar == 13)
                {
                    if (rdbtnReceiveTask.Checked)
                    {
                        ReceiveTask();
                    }
                    else
                    {

                        CompleteTech();

                    }

                    txtProductBarCode.Text = string.Empty;
                    txtProductBarCode.Focus();

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        /// <summary>
        /// 接收任务
        /// </summary>
        private void ReceiveTask()
        {
            try
            {
                string msg = "";


                if (!string.IsNullOrEmpty(txtProductBarCode.Text.Trim()))
                {
                    string orderbarcode = "";
                    if (comboBoxScantype.SelectedIndex == 0)
                    {
                        orderbarcode = FormatProductCode();
                    }
                    else
                    {
                        orderbarcode = _presenter.GetProductCodeByPhotoID(GetphotoID());
                    }

                    int currentTechId = _presenter.GetCurrentTechIdByOrderProductId(orderbarcode, out msg);
                    if (currentTechId == -2)
                    {
                        MessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    if (currentTechId == -1)
                    {
                        MessageBox.Show("产品流程已完成或产品无流程！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    if (currentTechId == 0)
                    {
                        MessageBox.Show("产品号不存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    int ret = _presenter.ReceiveTask(currentTechId, userId, orderbarcode);
                    if (ret == 0)
                    {
                        lbMsg.Text = "产品号：" + orderbarcode + "接收成功！";
                        _speech.Speak("接收成功");
                        _presenter.ShowTask(userId);
                        if (checkBoDisplaypic.Checked)
                        {
                            splitContainer1.Panel2Collapsed = false;
                            splitContainer1.Panel1Collapsed = false;
                            List<MINERP.BLL.QC.QCBLL.CheckPhoto> list = _presenter.GetPhotoList(orderbarcode);
                            AddThumbs(list);
                        }
                        if (Properties.Settings.Default.IsAutoPrintBarcode)//需要自动打印条码
                        {
                            this.CurrBarCode = orderbarcode;
                            _presenter.PrintBarcode();
                        }
                    }
                    else if (ret == -1)
                    {
                        lbMsg.Text = "产品号：" + orderbarcode + "接收失败！";
                        lbMsg.BackColor = Color.Red;
                    }
                    ShowOrderInfo(orderbarcode);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void AddThumbs(List<QCBLL.CheckPhoto> photos)
        {


            try
            {
                browser.Items.Clear();
                // RasterCodecs.Startup();
                RasterCodecs codecs = new RasterCodecs();
                CodecsThumbnailOptions option = new CodecsThumbnailOptions();
                option.LoadStamp = true;
                option.MaintainAspectRatio = true;
                option.Resample = true;
                //option.ForceSize = true;
                //option.bi
                RasterImage img;
                foreach (QCBLL.CheckPhoto p in photos)
                {
                    try
                    {
                        img = codecs.ReadThumbnail(p.PicPath, option, 1);
                    }
                    catch //没有缩略图就读取原图                    
                    {
                        img = codecs.Load(p.PicPath);
                    }

                    RasterImageListItem item = new RasterImageListItem(img, 1, p.PhotoRemark);
                    item.Tag = p.PicPath;
                    browser.Items.Add(item);
                }
                //RasterCodecs.Shutdown();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            //browser.SelectedIndexChanged += browser_SelectedIndexChanged;

        }

        /// <summary>
        /// 完成任务
        /// </summary>
        private void CompleteTech()
        {
            try
            {
                string msg = "";
                if (!string.IsNullOrEmpty(txtProductBarCode.Text.Trim()))
                {

                    string orderbarcode = "";
                    if (comboBoxScantype.SelectedIndex == 0)
                    {
                        orderbarcode = FormatProductCode();
                    }
                    else
                    {
                        orderbarcode = _presenter.GetProductCodeByPhotoID(GetphotoID());
                    }
                    int currentTechId = _presenter.GetCurrentTechIdByOrderProductId(orderbarcode, out msg);
                    if (currentTechId == -2)
                    {
                        MessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    if (currentTechId == -1)
                    {
                        MessageBox.Show("产品流程已完成或产品无流程！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    if (currentTechId == 0)
                    {
                        MessageBox.Show("产品号不存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    if (operates.ContainsKey(currentTechId))
                    {
                    
                        bool ret = _presenter.CompleteTech(currentTechId, userId, orderbarcode, operates);

                        if (ret)
                        {
                            string techName = operates.First(p => p.Key == currentTechId).Value;
                            lbMsg.Text = "产品：" + orderbarcode + "在岗位" + techName + "提交成功！";
                            _speech.Speak(techName);
                           // _presenter.ShowTask(userId);
                           // _presenter.ShowTask(taskTechlist);
                            if (Properties.Settings.Default.IsAutoPrintBarcode)//完成时需要自动打印条码
                            {
                                this.CurrBarCode = orderbarcode;
                                if (Properties.Settings.Default.IsAutoPrintBarcode)
                                {
                                    _presenter.PrintBarcode();
                                }
                            }
                            if (checkBoDisplaypic.Checked)
                            {
                                splitContainer1.Panel2Collapsed = false;
                                splitContainer1.Panel1Collapsed = false;
                                List<MINERP.BLL.QC.QCBLL.CheckPhoto> list = _presenter.GetPhotoList(orderbarcode);
                                AddThumbs(list);
                            }
                           
                        }
                        else
                        {
                            lbMsg.Text = "产品号：" + orderbarcode + "提交失败！";
                            lbMsg.BackColor = Color.Red;
                        }
                        ShowOrderInfo(orderbarcode);
                        List<TaskInfo> Tasklist = new List<TaskInfo>();
                        Tasklist = ListTask;
                        for (int i = 0; i < Tasklist.Count(); i++)
                        {
                            if (Tasklist[i].OrderProductId == Convert.ToInt32(txtProductBarCode.Text.Trim()))
                            {
                                ListTask.RemoveAt(i);//将符合条件的下标移除
                                break;
                            }

                        }
                        gcTask.DataSource = ListTask;
                        gcTask.RefreshDataSource();
                    }
                    else
                    {
                        MessageBox.Show("该产品流程不在本岗位！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 显示产品信息
        /// </summary>
        /// <param name="OrderProductCode"></param>
        private void ShowOrderInfo(string orderProductcode)
        {
            List<TaskInfo> taskList = gcTask.DataSource as List<TaskInfo>;
            TaskInfo task = taskList.FirstOrDefault(t => t.OrderProductCode == orderProductcode);
            if (task != null)
            {
                lbCtmName.Text = task.CtmName;
                lbPageNum.Text = task.PageNum.ToString();
                lbProductName.Text = task.OrderProductName;
                lbRemark.Text = task.ProductRemark;
                lbShopName.Text = task.ShopName;
            }
            else
            {
                task = _presenter.GetTaskInfo(orderProductcode);
                lbCtmName.Text = task.CtmName;
                lbPageNum.Text = task.PageNum.ToString();
                lbProductName.Text = task.OrderProductName;
                lbRemark.Text = task.ProductRemark;
                lbShopName.Text = task.ShopName;
            }
        }

        private void rdbtnReceiveTask_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbtnReceiveTask.Checked)
            {
                rdbtnCompleteTask.Checked = false;
            }
            else
            {
                rdbtnCompleteTask.Checked = true;
            }
        }

        private void rdbtnCompleteTask_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbtnCompleteTask.Checked)
            {
                rdbtnReceiveTask.Checked = false;
            }
            else
            {
                rdbtnReceiveTask.Checked = true;
            }
        }

        private void tsbtnBarcode_Click(object sender, EventArgs e)
        {
            if (txtProductBarCode.Text.Trim() != string.Empty)
            {
                this.CurrBarCode = FormatProductCode();
                _presenter.PrintBarcode();
            }
            else
            {
                MessageBox.Show("请输入产品号！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void chkPrintBarcode_CheckedChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.IsAutoPrintBarcode = chkPrintBarcode.Checked;
            Properties.Settings.Default.Save();
        }

        private string FormatProductCode()
        {

            string code = txtProductBarCode.Text.Trim();
            if (code.Length < 10)
            {
                int c = Convert.ToInt32(code);
                code = "2" + string.Format("{0:d9}", c);
            }
            return code;
        }
        private int GetphotoID()
        {

            string code = txtProductBarCode.Text.Trim();

            int c = Convert.ToInt32(code);

            return c;
        }
        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            RasterCodecs.Shutdown();
        }

        private void comboBoxScantype_DropDownClosed(object sender, EventArgs e)
        {
            Properties.Settings.Default.Scantype = comboBoxScantype.SelectedIndex;
            Properties.Settings.Default.Save();
        }

        private void gvTask_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            GridCell cell=sender as GridCell;
            
        }

    }
}
